﻿using UnityEngine;
using UnityEngine.InputSystem;
using Zenject;

public class PlayerMovement : MonoBehaviour
{
    private PlayerInputActions playerInputActions;
    private PlayerHealth playerHealth;
    private Rigidbody2D rigidbody2D;
    private Animator animator;
    [Header("移动")] [SerializeField] private float speed = 5;
    [SerializeField] private GameObject body;
    private Vector2 moveInput;
    private bool isFacingRight = true;
    public readonly static int isMoving = Animator.StringToHash("isMoving");
    [Inject] private GameManager _gameManager;


    private void Awake()
    {
        playerInputActions = new PlayerInputActions();
        rigidbody2D = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        playerHealth = GetComponent<PlayerHealth>();
    }

    private void Update()
    {
        if (playerHealth.isDead)
        {
            return;
        }

        HandleMoveInput();
        HandleFlip();
        HandleAnimation();
    }

    private void HandleAnimation()
    {
        animator.SetBool(isMoving, rigidbody2D.velocity.magnitude > 0);
    }

    private void HandleFlip()
    {
        if (moveInput.x < 0 && isFacingRight || moveInput.x > 0 && !isFacingRight)
        {
            Flip();
        }
    }

    private void HandleMoveInput()
    {
        // transform.Translate(moveInput * Time.deltaTime * 5);
        //用rigidbody来移动
        rigidbody2D.velocity = new Vector2(moveInput.normalized.x, moveInput.normalized.y) * speed;
    }


    private void Flip()
    {
        body.transform.Rotate(0, 180, 0);
        isFacingRight = !isFacingRight;
    }


    private void OnEnable()
    {
        playerInputActions.Player.Enable();
        playerInputActions.Player.Movement.performed += OnMove;
        playerInputActions.Player.Movement.canceled += OnMove;
    }

    private void OnMove(InputAction.CallbackContext obj)
    {
        moveInput = obj.ReadValue<Vector2>();
    }

    private void OnDisable()
    {
        playerInputActions.Player.Disable();
        playerInputActions.Player.Movement.performed -= OnMove;
        playerInputActions.Player.Movement.canceled -= OnMove;
    }
}